<template>
  <div ref="chartRef" :style="{
    width: ' 100 %',
    height: proxy.$size(height, '320px'),
  }">
  </div>
</template>
<script setup lang="ts">
import * as echarts from 'echarts';
import { onMounted, getCurrentInstance, onUnmounted } from 'vue';
const { proxy } = getCurrentInstance() as any;
const props = withDefaults(
  defineProps<{
    data?: any;
    height?: string | number;
    seriesSet?: any;
  }>(),
  {
    data: {
      strength: 80,//力量
      agility: 80,//敏捷
      stamina: 90,//耐力
      intelligence: 50,//智力
      spirit: 60,//精神
    },
  },
);
// 获取 DOM 元素的引用
const chartRef = ref<HTMLDivElement | null>(null);
let chartInstance: echarts.ECharts | null = null;
onMounted(() => {
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value);
    const _setData: any = {
      name: '角色属性',//名称
      color: '#5470c6',//颜色
      indicator: [
        {
          name: '力量',
          key: 'agility',
          max: 100
        },
        {
          name: '敏捷',
          key: 'strength',
          max: 100
        },
        {
          name: '耐力',
          key: 'stamina',
          max: 100
        },
        {
          name: '智力',
          key: 'intelligence',
          max: 100
        },
        {
          name: '精神',
          key: 'spirit',
          max: 100
        }
      ],
      ...props.seriesSet,
    }
    // 定义图表的配置项和数据
    const option = {
      //开启提示
      tooltip: {
        trigger: 'item'
      },
      //画图布局
      grid: {
        left: '3%',
        right: '3%',
        bottom: '3%',
        top: '3%',
        containLabel: true
      },
      radar: {
        indicator: _setData.indicator
      },
      series: [
        {
          type: 'radar',
          data: _setData.data || [{
            name: _setData.name,
            value: objToArr(props.data, _setData.indicator)
          }],
          itemStyle: {
            color: _setData.color
          },
          areaStyle: {
            color: new echarts.graphic.RadialGradient(0.1, 1, 1, [
              {
                color: proxy.$hexAlpha(_setData.color, 0.2),
                offset: 0
              },
              {
                color: proxy.$hexAlpha(_setData.color, 1),
                offset: 1
              }
            ])
          }
        },
      ],
    };
    // 使用配置项和数据显示图表
    option && chartInstance.setOption(option);
  }
  // 监听窗口大小变化并调整图表大小
  window.addEventListener('resize', handleResize);
});
const objToArr = (row: any, indicator: any) => {
  let _arr: any[] = []
  if (row && indicator) {
    _arr = indicator?.map((el: any) => row[el.key] || 0)
  }
  return _arr
};
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};
onUnmounted(() => {
  // 清理事件监听器
  window.removeEventListener('resize', handleResize);
  // 销毁图表实例
  if (chartInstance) {
    chartInstance.dispose();
  }
});
</script>
<style scoped lang="scss"></style>
